package com.demo.advice;

import com.demo.common.support.builder.ResponseBuilder;
import com.demo.common.support.model.DataResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * 返回值统一处理
 *
 * @author molong
 * @since 2024/5/24
 */
@RestControllerAdvice
public class RestControllerCommonAdvice implements ResponseBodyAdvice<Object> {

    @Resource
    private IgnoredConfig ignoredConfig;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(o instanceof DataResponse){
            //如果已经为封装好的内容直接返回
            return o;
        }
        //白名单请求直接放行
        PathMatcher pathMatcher = new AntPathMatcher();
        for (String path : ignoredConfig.getUrls()) {
            if(pathMatcher.match(path, serverHttpRequest.getURI().getPath())){
                //匹配不做任何处理
                return o;
            }
        }
        return ResponseBuilder.start().data(o).build();
    }
}
